/**
 * SysCommentServiceImpl.java -- 2017-10-20 13:40:09 作者：欧增奇 -- 代码生成器自动生成 联系方式：425752797@qq.com http://www.ouzengqi.com/
 */
package com.ozq.sys.service.impl;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.ozq.common.page.Page;
import com.ozq.common.page.PageUtil;
import com.ozq.common.util.CommonUtils;
import com.ozq.common.util.UuidUtils;
import com.ozq.sys.dao.entity.SysComment;
import com.ozq.sys.dao.entity.SysText;
import com.ozq.sys.dao.mapper.SysCommentMapper;
import com.ozq.sys.dao.mapper.SysTextMapper;
import com.ozq.sys.service.inter.SysCommentService;

/**
 * <评论表接口实现> <功能详细描述>
 * 
 * @author 欧增奇
 * @version [V2.0, 2017-10-20 13:40:09]
 * @see [相关类/方法]
 * @since [产品/模块版本]
 */
@Service("sysCommentService")
public class SysCommentServiceImpl implements SysCommentService
{
    static Logger logger = LoggerFactory.getLogger(SysCommentServiceImpl.class);

    /**
     * 评论表Mapper[SysComment]
     */
    @Autowired
    private SysCommentMapper sysCommentMapper;

    /**
     * 系统-文本表Mapper[SysText]
     */
    @Autowired
    private SysTextMapper sysTextMapper;

    /** ------------------------------------公共-工具------------------------------------ **/
    /**
     * 分页公共实现
     */
    @Override
    public Page pageManage(Page page)
    {
        logger.debug("debug page: {}", page);

        // 默认每页10条记录
        if (page.getEveryPage() <= 0)
            page.setEveryPage(10);

        // 默认第一页
        if (page.getCurrentPage() <= 0)
            page.setCurrentPage(1);

        return PageUtil.createPage(page.getEveryPage(), page.getTotalCount(), page.getCurrentPage());
    }

    /**
     * 缓存清理
     */
    @Override
    public void clearCache()
    {
        logger.debug("清理评论表缓存成功:{}", "sysComment");
    }

    /** ------------------------------------公共-业务------------------------------------ **/
    /** --公共-业务-统计-- **/
    /**
     * 统计评论表所有的记录数
     * 
     * @return int
     */
    @Override
    public int countAll()
    {
        return sysCommentMapper.countAll();
    }

    /**
     * 按照条件精确统计评论表
     * 
     * @param sysComment
     * @return int
     */
    @Override
    public int countBy(SysComment sysComment)
    {
        logger.debug("debug sysComment: {}", sysComment);

        if (sysComment == null)
            return 0;

        return sysCommentMapper.countBy(sysComment);
    }

    /**
     * 按照条件模糊统计评论表
     * 
     * @param sysComment
     * @return int
     */
    @SuppressWarnings("deprecation")
    @Override
    public int countLike(SysComment sysComment)
    {
        logger.debug("debug sysComment: {}", sysComment);

        if (sysComment == null)
            return 0;

        String selectSQL = "";
        selectSQL += " SELECT COUNT(1) countVal";
        selectSQL += " FROM sys_comment sc";

        Map<String, Object> whereMap = new HashMap<>();
        whereMap.put("article_code", sysComment.getArticleCode());
        whereMap.put("comment_type", sysComment.getCommentType());
        whereMap.put("comment_status", 1);
        selectSQL = CommonUtils.getSelectSQLWhere(whereMap, true, selectSQL);

        selectSQL += " limit 1";

        List<Map<String, Object>> listMap = sysCommentMapper.selectCustom(selectSQL);
        if (listMap == null || listMap.isEmpty())
            return 0;

        Long countVal = (Long) listMap.get(0).get("countVal");
        return countVal.intValue();
    }

    /** --公共-业务-添加-- **/
    /**
     * 插入评论表
     * 
     * @param sysComment
     * @return sysComment
     */
    @Override
    public SysComment add(SysComment sysComment)
    {
        logger.debug("debug sysComment: {}", sysComment);

        if (sysComment == null)
            return null;

        // 过滤数据
        sysComment.setTextCode(CommonUtils.filterScript(sysComment.getTextCode()));

        SysText sysText = new SysText();
        sysText.setTextCode(UuidUtils.shortUuid());
        sysText.setTextContent(sysComment.getTextCode());
        sysTextMapper.insert(sysText);

        if (StringUtils.isBlank(sysComment.getCommentCode()))
        {
            sysComment.setCommentCode(UuidUtils.shortUuid());
        }
        sysComment.setTextCode(sysText.getTextCode());
        sysCommentMapper.insert(sysComment);
        return sysComment;
    }

    /**
     * 插入评论表集合
     * 
     * @param sysComment
     * @return boolean
     */
    @Override
    public boolean addList(List<SysComment> sysComments)
    {
        logger.debug("debug sysComments: {}", sysComments);

        if (sysComments == null || sysComments.isEmpty())
            return false;

        List<SysComment> inserts = filterEmpty(sysComments);
        if (inserts.isEmpty())
            return false;

        sysCommentMapper.insertList(inserts);
        return true;
    }

    /**
     * 批量插入评论表，当id存在更新这条数据，不存在插入这条数据（注意：会影响所有字段）
     * 
     * @param sysComments
     * @return boolean
     */
    @Override
    public boolean addUpdateList(List<SysComment> sysComments)
    {
        logger.debug("debug sysComments: {}", sysComments);

        if (sysComments == null || sysComments.isEmpty())
            return false;

        List<SysComment> inserts = filterEmpty(sysComments);
        if (inserts.isEmpty())
            return false;

        sysCommentMapper.insertUpdateList(inserts);
        return true;
    }

    /** --公共-业务-查询-- **/
    /**
     * 按照评论表查询,如果存在id，则用id查询(本方法只会返回一条数据，当查询有1条以上返回null)
     * 
     * @param sysComment
     * @return sysComment
     */
    @Override
    public SysComment find(SysComment sysComment)
    {
        logger.debug("debug sysComment: {}", sysComment);

        if (sysComment == null)
            return null;

        if (sysComment.getCommentId() != null)
            return sysCommentMapper.selectById(sysComment.getCommentId());

        sysComment.setStartLine(0);
        sysComment.setEndLine(1);
        List<SysComment> list = sysCommentMapper.listBy(sysComment);
        if (list == null || list.isEmpty())
            return null;

        return list.get(0);
    }

    /**
     * 按照id查询评论表
     * 
     * @param commentId
     * @return sysComment
     */
    @Override
    public SysComment findById(Integer commentId)
    {
        logger.debug("debug commentId: {}", commentId);

        if (commentId == null)
            return null;

        return sysCommentMapper.selectById(commentId);
    }

    /**
     * 按照ids查询评论表
     * 
     * @param commentIds
     * @return sysComment集合
     */
    @Override
    public List<SysComment> findByIds(List<Integer> commentIds)
    {
        logger.debug("debug commentIds: {}", commentIds);

        if (commentIds == null || commentIds.isEmpty())
            return null;

        return sysCommentMapper.selectByIds(commentIds);
    }

    /**
     * 按照条件精确查询评论表返回集合方法
     * 
     * @param sysComment
     * @return sysComment
     */
    @Override
    public List<SysComment> listBy(SysComment sysComment)
    {
        logger.debug("debug sysComment: {}", sysComment);

        if (sysComment == null)
            return null;

        return sysCommentMapper.listBy(sysComment);
    }

    /**
     * 按照条件模糊查询评论表返回集合方法
     * 
     * @param sysComment
     * @return sysComment集合
     */
    @SuppressWarnings("deprecation")
    @Override
    public List<Map<String, Object>> listLike(SysComment sysComment)
    {
        logger.debug("debug sysComment: {}", sysComment);

        if (sysComment == null)
            return null;

        String selectSQL = "";
        selectSQL += " SELECT (";
        selectSQL += "     SELECT user_figure_url";
        selectSQL += "     FROM sys_user su";
        selectSQL += "     WHERE su.user_code = sc.user_code";
        selectSQL += " ) AS user_figure_url,(";
        selectSQL += "     SELECT user_nick_name";
        selectSQL += "     FROM sys_user su";
        selectSQL += "     WHERE su.user_code = sc.user_code";
        selectSQL += " ) AS user_nick_name,COUNT(1) AS count_article";
        selectSQL += " FROM sys_comment sc";
        selectSQL += " WHERE comment_type=1 AND comment_status=1";
        selectSQL += " GROUP BY user_code";
        selectSQL += " ORDER BY count_article DESC";
        selectSQL += " limit 6";

        return sysCommentMapper.selectCustom(selectSQL);
    }

    /**
     * 按照分页条件精确查询评论表返回集合方法
     * 
     * @param sysComment
     * @return sysComment集合
     */
    @Override
    public List<SysComment> listPageBy(Page page, SysComment sysComment)
    {
        logger.debug("debug page: {}", page);
        logger.debug("debug sysComment: {}", sysComment);

        if (sysComment == null)
            sysComment = new SysComment();

        if (page != null)
        {
            sysComment.setStartLine(page.getBeginIndex());
            sysComment.setEndLine(page.getEveryPage());
        }

        if (sysComment.getOrderBy() == null)
            sysComment.setOrderBy(SysComment.FIELD_COMMENT_ADD_TIME + SysComment.ORDER_BY_DESC);

        return sysCommentMapper.listBy(sysComment);
    }

    /**
     * 按照分页条件模糊查询评论表返回集合方法
     * 
     * @param sysComment
     * @return sysComment集合
     */
    @SuppressWarnings("deprecation")
    @Override
    public List<Map<String, Object>> listPageLike(Page page, SysComment sysComment)
    {
        logger.debug("debug page: {}", page);
        logger.debug("debug sysComment: {}", sysComment);

        if (sysComment == null)
            sysComment = new SysComment();

        String selectSQL = "";
        selectSQL += " SELECT sc.*,(";
        selectSQL += "     SELECT user_figure_url";
        selectSQL += "     FROM sys_user su";
        selectSQL += "     WHERE su.user_code = sc.user_code";
        selectSQL += " ) AS user_figure_url,(";
        selectSQL += "     SELECT user_nick_name";
        selectSQL += "     FROM sys_user su";
        selectSQL += "     WHERE su.user_code = sc.user_code";
        selectSQL += " ) AS user_nick_name,(";
        selectSQL += "     SELECT text_content";
        selectSQL += "     FROM sys_text su";
        selectSQL += "     WHERE su.text_code = sc.text_code";
        selectSQL += " ) AS text_content,(";
        selectSQL += "     SELECT GROUP_CONCAT(CONCAT(";
        selectSQL += "         'user_figure_url',";
        selectSQL += "         (";
        selectSQL += "             SELECT user_figure_url";
        selectSQL += "             FROM sys_user su";
        selectSQL += "             WHERE su.user_code = csr.user_reply_code";
        selectSQL += "         ),'user_nick_name',(";
        selectSQL += "             SELECT user_nick_name";
        selectSQL += "             FROM sys_user su";
        selectSQL += "             WHERE su.user_code = csr.user_reply_code";
        selectSQL += "         ),'text_content',(";
        selectSQL += "             SELECT text_content";
        selectSQL += "             FROM sys_text su";
        selectSQL += "             WHERE su.text_code = csr.text_code";
        selectSQL += "         ),'comment_add_time',comment_add_time";
        selectSQL += "     ) SEPARATOR ';user_reply;')";
        selectSQL += "     FROM sys_comment csr";
        selectSQL += "     WHERE csr.user_code=sc.user_code AND csr.comment_code=sc.comment_code AND (csr.comment_type-1)=sc.comment_type";
        selectSQL += " ) AS reply";
        selectSQL += " FROM sys_comment sc";

        Map<String, Object> whereMap = new HashMap<>();
        whereMap.put("article_code", sysComment.getArticleCode());
        whereMap.put("comment_type", sysComment.getCommentType());
        whereMap.put("comment_status", 1);
        selectSQL = CommonUtils.getSelectSQLWhere(whereMap, true, selectSQL);
        if (sysComment.getCommentType() == 1)
            selectSQL += " ORDER BY comment_add_time ASC";
        else
            selectSQL += " ORDER BY comment_add_time DESC";

        if (page != null)
        {
            selectSQL += " limit " + page.getBeginIndex() + ", " + page.getEveryPage();
        }

        return sysCommentMapper.selectCustom(selectSQL);
    }

    /** --公共-业务-修改-- **/
    /**
     * 修改评论表
     * 
     * @param sysComment
     * @return boolean
     */
    @Override
    public boolean update(SysComment sysComment)
    {
        logger.debug("debug sysComment: {}", sysComment);

        if (sysComment == null || sysComment.getCommentId() == null)
            return false;

        sysCommentMapper.update(sysComment);
        return true;
    }

    /**
     * 批量修改评论表
     * 
     * @param sysComments
     * @return boolean
     */
    @Override
    public boolean updateList(List<SysComment> sysComments)
    {
        logger.debug("debug sysComments: {}", sysComments);

        if (sysComments == null)
            return false;

        List<SysComment> news = new ArrayList<SysComment>();
        for (SysComment sysComment : sysComments)
            if (sysComment != null && sysComment.getCommentId() != null)
                news.add(sysComment);

        if (news.isEmpty())
            return false;

        sysCommentMapper.updateList(news);
        return true;
    }

    /** --公共-业务-删除-- **/
    /**
     * 指定id删除
     * 
     * @param commentId
     * @return boolean
     */
    @Override
    public boolean deleteById(Integer commentId)
    {
        logger.debug("debug commentId: {}", commentId);

        if (commentId == null)
            return false;

        sysCommentMapper.deleteById(commentId);
        return true;
    }

    /**
     * 批量删除指定ids
     * 
     * @param commentId
     * @return boolean
     */
    @Override
    public boolean deleteByIds(List<Integer> commentIds)
    {
        logger.debug("debug commentIds: {}", commentIds);

        if (commentIds == null || commentIds.isEmpty())
            return false;

        sysCommentMapper.deleteByIds(commentIds);
        return true;
    }

    /**
     * 按照条件精确删除评论表
     * 
     * @param sysComment
     * @return boolean
     */
    @Override
    public boolean deleteBy(SysComment sysComment)
    {
        logger.debug("debug sysComment: {}", sysComment);

        if (sysComment == null)
            return false;

        sysCommentMapper.deleteBy(sysComment);
        return true;
    }

    /**
     * 按照条件模糊删除评论表
     * 
     * @param sysComment
     * @return boolean
     */
    @Override
    public boolean deleteLike(SysComment sysComment)
    {
        logger.debug("debug sysComment: {}", sysComment);

        if (sysComment == null)
            return false;

        sysCommentMapper.deleteLike(sysComment);
        return true;
    }

    /** --公共-业务-自定义-- **/
    /**
     * 自定义方法
     * 
     * @param sysComment
     * @return map集合
     */
    @Override
    public List<Map<String, Object>> custom(SysComment sysComment)
    {
        logger.debug("debug sysComment: {}", sysComment);

        // 自己实现自己的业务
        // sysCommentMapper.selectCustom(selectSQL);
        return null;
    }

    /** ------------------------------------私有-方法------------------------------------ **/
    /**
     * 过滤参数为空
     * 
     * @param sysComments
     * @return sysComment集合
     */
    private List<SysComment> filterEmpty(List<SysComment> sysComments)
    {
        List<SysComment> news = new ArrayList<SysComment>();
        for (SysComment sysComment : sysComments)
            if (sysComment != null)
                news.add(sysComment);
        return news;
    }
}